<?php

class Tag_Model_Entry
{
	protected $_id = NULL;
	protected $_idname = NULL;
	protected $_text = NULL;


    public function __construct(array $options = null)
    {
        if (is_array($options)) {
            $this->setOptions($options);
        }
    }


	public function setId($id = NULL)
	{
		$this->_id = $id;
		return $this;
	}
	public function setIdName($idname = NULL)
	{
		$this->_idname = $idname;
		return $this;
	}
	public function setText($text = NULL)
	{
		$this->_text = $text;
		return $this;
	}

	public function getId()
	{
		return $this->_id;
	}
	public function getIdName()
	{
		return $this->_idname;
	}
	public function getText()
	{
		return $this->_text;
	}


    public function __set($name, $value)
    {
        $method = 'set' . ucfirst($name);
        $this->$method($value);
    }
    public function __get($name)
    {
        $method = 'get' . ucfirst($name);
        return $this->$method();
    }

    public function setOptions(array $options)
    {
        $methods = get_class_methods($this);
        foreach ($options as $key => $value) {
            $method = 'set' . ucfirst($key);
            if (in_array($method, $methods)) {
                $this->$method($value);
            }
        }
        return $this;
    }


	protected static $_instanceList = array();


	/**
	 * Queries for a loaded instance.
	 */
	public static function findInstanceById($id = null)
	{
		if (intval($id) > 0 && isset(self::$_instanceList[$id]) === TRUE) {
			return self::$_instanceList[$id];
		}
		return NULL;
	}

	/**
	 * Queries for an instance. If the instance is not found, it will be loaded from the database.
	 */
	public static function getInstanceById($id)
	{
		$key = 'id'; //HACK
		$value = $id;

		if ($key === 'id') {
			$inst = self::findInstanceById($value);
		} else if ($key === 'idname') {
			$inst = self::findInstanceByIdName($value);
			$value = strtolower($value);
		} else {
			return NULL;
		}

		if ($inst instanceof Post_Model_Entry) {
			return $inst;
		}

		$inst = new Post_Model_Entry();

		$table = Post_Model_DbTable_Entry::getInstance();

		$select = $table->select();
		$select->where($key .'= ?', $value);

		$dbResult = $table->fetchAll($select);

		if ($dbResult->count() !== 1) {
			return NULL;
		}

		$dbRow = $dbResult->getRow(0);
		$inst
			->setId($dbRow->id)
			->setIdName($dbRow->idname)
			->setText($dbRow->text)
		;

		self::$_instanceList[$dbRow->id] = $inst;

		return $inst;
	}
}
